/*
 * Copyright 2006 - Chris Maki
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.theserverside.blog.dao.jpa;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;

import com.theserverside.blog.dao.GenericDao;
import com.theserverside.blog.dao.NamedQueryParameter;
import com.theserverside.blog.dao.QueryParameter;
import com.theserverside.blog.dao.QueryParameter.TemporalType;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


/**
 * Many portions of this class are taken from the following examples:
 * <ul>
 *   <li><a href="http://www.hibernate.org/328.html">http://www.hibernate.org/328.html
 *   <li><a href="http://www-128.ibm.com/developerworks/java/library/j-genericdao.html">http://www-128.ibm.com/developerworks/java/library/j-genericdao.html</a>
 *   <li><a href="http://blog.diefirma.de/2006-01-10/using-the-new-java-persistence-api-with-spring/">http://blog.diefirma.de/2006-01-10/using-the-new-java-persistence-api-with-spring/</a>
 *   <li> and some from the JPA specification
 * </ul>
 * @author chrismaki
 * 
 * @param <T> The domain model object we are providing DAO services for
 * @param <PK> The primary key type of T
 */
public class GenericDaoJpa<T, PK extends Serializable> implements GenericDao<T, PK> {

    @PersistenceContext(type=PersistenceContextType.EXTENDED)
    protected EntityManager entityManager;
    protected Class<T> type;
    
    
    public void setType(Class<T> type) {
		this.type = type;
	}

	/**
	 * This is a convenience constructor, if you don't want to declare a
	 * specific DAO class, that is to say the methods defined in GenericDao are
	 * sufficient, then you this constructor and you'll have a type safe,
	 * generic DAO implementation.
	 * 
	 * @param type the model type you are providing DAO services for
	 */
    public GenericDaoJpa(final Class<T> type) {
    	this.type = type;
    }
    
    /**
	 * This is the default constructor, if you subclass this class, all you need
	 * to do is define the type of the subclass and GenericDaoJpa will have the
	 * correct type. Here is how you would subclass GenericDaoJpa:
	 * 
	 * <pre>
	 * <code>
	 * public class ForumDaoJpa extends GenericDaoJpa&lt;Forum, Long&gt; implements ForumDao
	 * </code>
	 * </pre>
	 */
    public GenericDaoJpa() {
        @SuppressWarnings("unchecked")
        Class<T> aType = (Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
        this.type = aType;
    }
    
    // By default, an EM is a transaction-scoped EntityManager.
    @PersistenceContext(type=PersistenceContextType.EXTENDED)
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
    
    public EntityManager getEntityManager() {
        return entityManager;
    }
    
    public List<T> findAll() {
        
        @SuppressWarnings("unchecked")
        List<T> results = entityManager.createQuery("select o from " + type.getSimpleName() + " o").getResultList();
        
        return results;
    }
	
	public T findByPk(PK pk) {

        return entityManager.find(type, pk);
    }

    public void persist(Object object) {
        entityManager.persist(object);
    }
	
    public void flush() {
        entityManager.flush();
        
    }

    public void clear() {
        entityManager.clear();
    }
    
    public void remove(Object object) {
    	if (!entityManager.contains(object)) {
    		// if object isn't managed by EM, load it into EM
    		object = entityManager.merge(object);
    	}
    	// object is now a managed object so it can be removed.
        entityManager.remove(object);
    }
	
    public Object merge(Object object) {
		return entityManager.merge(object);
	}

    @SuppressWarnings("unchecked")
    public List executeJpql(String query) {
	    return entityManager.createQuery(query).getResultList();
	}

	public List<T> findByNamedQuery(String queryName) {
		Query q = entityManager.createNamedQuery(queryName);
		
		@SuppressWarnings("unchecked")
		List<T> result = q.getResultList();
		
 		return result;
	}

	public List<T> findByNamedQueryNamedParameter(String queryName, String name, Object value) {
		return findByNamedQueryNamedParameter(queryName, new NamedQueryParameter(name, value));
	}

	public List<T> findByNamedQueryNamedParameter(String queryName, String name, Object value, TemporalType type) {
		return findByNamedQueryNamedParameter(queryName, new NamedQueryParameter(name, value, type));
	}

	public List<T> findByNamedQueryNamedParameter(String queryName, NamedQueryParameter... args) {
		Query q = getAndCreateQueryNamedParameters(queryName, args);
		
		@SuppressWarnings("unchecked")
		List<T> result = q.getResultList();
		
		return result;
	}
	
	public List<T> findByNamedQueryPositionalParameter(String queryName, QueryParameter... args) {
		Query q = getAndCreateQueryPositionalParameters(queryName, args);
		
		@SuppressWarnings("unchecked")
		List<T> results = q.getResultList();
		
		return results;
	}

	@Transactional(noRollbackFor={NoResultException.class, NonUniqueResultException.class}, propagation=Propagation.SUPPORTS)
	public T findInstanceByNamedQuery(String queryName) {
		Query q = entityManager.createNamedQuery(queryName);
		
		@SuppressWarnings("unchecked")
		T result = (T) q.getSingleResult();
		
 		return result;	
	}

	@Transactional(noRollbackFor={NoResultException.class, NonUniqueResultException.class}, propagation=Propagation.SUPPORTS)
	public T findInstanceByNamedQueryNamedParameter(String queryName, NamedQueryParameter... args) {
		Query q = getAndCreateQueryNamedParameters(queryName, args);
		
		@SuppressWarnings("unchecked")
		T result = (T) q.getSingleResult();
		
		return result;
	}

	@Transactional(noRollbackFor={NoResultException.class, NonUniqueResultException.class}, propagation=Propagation.SUPPORTS)
	public T findInstanceByNamedQueryPositionalParameter(String queryName, QueryParameter... args) {
		Query q = getAndCreateQueryPositionalParameters(queryName, args);
		
		@SuppressWarnings("unchecked")
		T result = (T) q.getSingleResult();
		
		return result;
	}
	

	private Query getAndCreateQueryNamedParameters(String queryName, NamedQueryParameter... args) {
	
		Query q = entityManager.createNamedQuery(queryName);
   		populateQueryNamedParameter(q, args);
			
		return q;
	}

	private void populateQueryNamedParameter(Query q, NamedQueryParameter... args) {
		
		if (args != null) {
			
			for(NamedQueryParameter qp : args) {
				if (qp.getType() == null || qp.getType() == TemporalType.NONE) {
					q.setParameter(qp.getParameterName(), qp.getValue());
				} else {
					switch (qp.getType()) {
					case DATE:
						if (qp.getValue() instanceof Date) {
							q.setParameter(qp.getParameterName(), (Date) qp.getValue(), javax.persistence.TemporalType.DATE);
						} else if (qp.getValue() instanceof Calendar) {
							q.setParameter(qp.getParameterName(), (Calendar) qp.getValue(), javax.persistence.TemporalType.DATE);
						} else {
							q.setParameter(qp.getParameterName(), qp.getValue());
					}
						break;
					case TIME: 
						if (qp.getValue() instanceof Date) {
							q.setParameter(qp.getParameterName(), (Date) qp.getValue(), javax.persistence.TemporalType.TIME);
						} else if (qp.getValue() instanceof Calendar) {
							q.setParameter(qp.getParameterName(), (Calendar) qp.getValue(), javax.persistence.TemporalType.TIME);
						} else {
							q.setParameter(qp.getParameterName(), qp.getValue());
						}
						break;
					case TIMESTAMP:
						if (qp.getValue() instanceof Date) {
							q.setParameter(qp.getParameterName(), (Date) qp.getValue(), javax.persistence.TemporalType.TIMESTAMP);
						} else if (qp.getValue() instanceof Calendar) {
							q.setParameter(qp.getParameterName(), (Calendar) qp.getValue(), javax.persistence.TemporalType.TIMESTAMP);
						} else {
							q.setParameter(qp.getParameterName(), qp.getValue());
						}
						break;
					}
				}
			}
		}
	}

	private Query getAndCreateQueryPositionalParameters(String queryName, QueryParameter... args) {
		
		Query q = entityManager.createNamedQuery(queryName);
		populateQueryPositionalParameters(q, args);
		
		return q;
	}

	private void populateQueryPositionalParameters(Query q, QueryParameter... args) {
		if (args != null) {
        
			int position = 1;
			
			for(QueryParameter qp : args) {
				if (qp.getType() == null || qp.getType() == TemporalType.NONE) {
					q.setParameter(position++, qp.getValue());
				} else {
					switch (qp.getType()) {
					case DATE:
						if (qp.getValue() instanceof Date) {
							q.setParameter(position++, (Date) qp.getValue(), javax.persistence.TemporalType.DATE);
						} else if (qp.getValue() instanceof Calendar) {
							q.setParameter(position++, (Calendar) qp.getValue(), javax.persistence.TemporalType.DATE);
						} else {
							q.setParameter(position++, qp.getValue());
						}
						break;
					case TIME: 
						if (qp.getValue() instanceof Date) {
							q.setParameter(position++, (Date) qp.getValue(), javax.persistence.TemporalType.TIME);
						} else if (qp.getValue() instanceof Calendar) {
							q.setParameter(position++, (Calendar) qp.getValue(), javax.persistence.TemporalType.TIME);
						} else {
							q.setParameter(position++, qp.getValue());
						}
						break;
					case TIMESTAMP:
						if (qp.getValue() instanceof Date) {
							q.setParameter(position++, (Date) qp.getValue(), javax.persistence.TemporalType.TIMESTAMP);
						} else if (qp.getValue() instanceof Calendar) {
							q.setParameter(position++, (Calendar) qp.getValue(), javax.persistence.TemporalType.TIMESTAMP);
						} else {
							q.setParameter(position++, qp.getValue());
						}
						break;
					}
				}
			}
		}
	}

	public List<T> find(String query) {
		Query q = entityManager.createQuery(query);
		
		@SuppressWarnings("unchecked")
		List<T> result = q.getResultList();
		
		return result;
	}

	public List<T> find(String query, Object value) {
		Query q = entityManager.createQuery(query);
		q.setParameter(1, value);
		
		@SuppressWarnings("unchecked")
		List<T> result = q.getResultList();
		
		return result;
	}

	public List<T> find(String query, String name, Object value) {
		Query q = entityManager.createQuery(query);
		q.setParameter(name, value);
		
		@SuppressWarnings("unchecked")
		List<T> result = q.getResultList();
		
		return result;
	}

	public List<T> findNamedParameter(String query, NamedQueryParameter... args) {
		Query q = entityManager.createQuery(query);
		populateQueryNamedParameter(q, args);

		@SuppressWarnings("unchecked")
		List<T> result = q.getResultList();
		
		return result;

	}

	public List<T> findPositionalParameter(String query, QueryParameter... args) {
		Query q = entityManager.createQuery(query);
		populateQueryPositionalParameters(q, args);

		@SuppressWarnings("unchecked")
		List<T> result = q.getResultList();
		
		return result;
	}

}
